const handler = (msgKey, onSuccess, onError, remove = true) => {
    let callback;
    const event = () => {
        const res = WPT.localStorage.getItem(msgKey);
        WPT.localStorage.clearItem(msgKey);
        if (res) {
            remove && callback && callback();
            try {
                const { data, error } = JSON.parse(res);
                data && onSuccess && onSuccess(data);
                error && onError && onError(error);
            } catch (e) {
                onError && onError(e);
            }
        }
    };
    window.addEventListener('storage', event);
    callback = () => {
        window.removeEventListener('storage', event);
    };
    return callback;
};

const openXcx = (type, eventId, args) => {
    const url = WPT.Util.urlAddQuery('/pages/h5-transmitter/index', {
        type,
        eventId,
        ...args,
    });
    WPT.execWxJob(() => {
        WPT.os.xcx && window.wx.miniProgram.navigateTo({ url });
    });
};

export const xcxAction = (type, args = {}) => {
    const eventId = WPT.Util.uuid();
    const msgKey = `${type}_${eventId}`;

    openXcx(type, eventId, args);

    return new Promise((resolve, reject) => {
        handler(msgKey, resolve, reject);
    });
};
